<template>
  <div>
    <a-card>
      <div style="display: flex">
        <div class="edit-title">
          <a-anchor :affix="false" :getContainer="gerGood" @click="anchorClick" :bounds="200">
            <a-anchor-link :href="item.herf" :title="item.title" class="handle-item" v-for="(item, index) in informationlist" :key="index" />
          </a-anchor>
        </div>
        <div style="width: 100%; height: 70vh">
          <div style="height: calc(100% - 40px); overflow-y: auto; margin-top: 16px" id="goods">
            <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol" style="width: 100%">
              <div id="components">
                <h1>基础设置</h1>
                <a-form-model-item ref="name" label="角色名称" prop="name">
                  <a-input
                    class="current"
                    :maxLength="20"
                    placeholder="请输入角色名称"
                    v-model.trim="form.name"
                    @blur="
                      () => {
                        $refs.name.onFieldBlur()
                      }
                    "
                  />
                </a-form-model-item>
                <a-form-model-item label="开通权限" prop="openAuth">
                  <a-checkbox-group v-model="form.openAuth" @change="onChangeOpenAuth">
                    <a-checkbox value="1" name="type"> 素材上传 </a-checkbox>
                    <a-checkbox value="2" name="type"> 素材审核 </a-checkbox>
                  </a-checkbox-group>
                </a-form-model-item>
                <a-form-model-item label="备注" prop="remark">
                  <a-textarea width="60%" v-model="form.remark" placeholder="请输入" :auto-size="{ minRows: 3, maxRows: 5 }" />
                </a-form-model-item>
              </div>
              <a-divider dashed />
              <div id="components-anchor" v-if="form.openAuth.includes('1')">
                <h1>上传权限配置</h1>
                <a-form-model-item label="上传品牌" prop="uploadBrandList">
                  <a-checkbox-group v-model="form.uploadBrandList">
                    <a-checkbox :value="item.key" v-for="item in brandList" :key="item.key"> {{ item.value }} </a-checkbox>
                  </a-checkbox-group>
                </a-form-model-item>
                <a-form-model-item label="发布方" prop="uploadPublisherList" class="">
                  <a-select style="width: 70%" v-model="form.uploadPublisherList" placeholder="请选择" show-search mode="multiple">
                    <a-select-option v-for="(item, index) in publisherList" :key="index" :value="item.key">{{ item.value }}</a-select-option>
                  </a-select>
                  <!-- <a-tree-select
                    show-search
                    style="width: 70%"
                    :value="form.uploadPublisherList"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    placeholder="请选择"
                    allow-clear
                    multiple
                    tree-default-expand-all
                    @change="changeMaterialType"
                  >
                  </a-tree-select> -->
                </a-form-model-item>
                <a-form-model-item label="素材分类" prop="uploadClassifyList" class="">
                  <a-tree-select
                    v-model="form.uploadClassifyList"
                    style="width: 70%"
                    :dropdownStyle="{ maxHeight: '476px' }"
                    :tree-data="classifyList"
                    :replaceFields="{ children: 'childList', title: 'name', key: 'code', value: 'code' }"
                    tree-checkable
                    allowClear
                    placeholder="请选择"
                    search-placeholder="Please select"
                    @change="onChange"
                  />
                </a-form-model-item>
              </div>
              <a-divider dashed />
              <div id="components-anchor-demo" v-if="form.openAuth.includes('2')">
                <h1>审核权限配置</h1>
                <a-form-model-item label="审核品牌" prop="approvalBrandList">
                  <a-checkbox-group v-model="form.approvalBrandList">
                    <a-checkbox :value="item.key" v-for="item in brandList" :key="item.key"> {{ item.value }} </a-checkbox>
                  </a-checkbox-group>
                </a-form-model-item>
                <a-form-model-item label="素材分类" prop="approvalClassifyList" class="">
                  <a-tree-select
                    v-model="form.approvalClassifyList"
                    style="width: 70%"
                    :dropdownStyle="{ maxHeight: '476px' }"
                    :tree-data="classifyList2"
                    :replaceFields="{ children: 'childList', title: 'name', key: 'code', value: 'code' }"
                    tree-checkable
                    allowClear
                    placeholder="请选择"
                    search-placeholder="Please select"
                    @change="onChange"
                  />
                </a-form-model-item>
                <a-form-model-item label="素材区域" prop="approvalAreaList" class="">
                  <a-tree-select
                    v-model="form.approvalAreaList"
                    style="width: 70%"
                    :dropdownStyle="{ maxHeight: '476px' }"
                    :tree-data="areaList"
                    tree-checkable
                    allowClear
                    placeholder="请选择区域"
                    search-placeholder="Please select"
                    @change="onChange"
                  />
                </a-form-model-item>
                <a-form-model-item label="审核节点" prop="approvalNodeList">
                  <a-checkbox-group v-model="form.approvalNodeList">
                    <a-checkbox :value="item.key" v-for="item in approvalNodeList" :key="item.key"> {{ item.value }} </a-checkbox>
                  </a-checkbox-group>
                </a-form-model-item>
              </div>
            </a-form-model>
          </div>
        </div>
      </div>
    </a-card>
    <div class="footer-box">
      <a-button @click="handleBack">取消</a-button>
      <a-button style="margin-left: 8px" @click="preservation" type="primary">确定</a-button>
    </div>
  </div>
</template>
<script>
import { publisher, themeDrand } from '@/api/pos/match'
import { roleDetail, themeClassify, areaList, nodeList, roleAdd } from '@/api/pos/authority'
export default {
  data() {
    return {
      id: this.$route.params.id, // 角色id
      brandList: [], // 上传品牌
      publisherList: [], // 发布方
      classifyList: [], // 素材分类 上传
      classifyList2: [], // 素材分类  审核
      approvalNodeList: [], // 审核节点

      manufacturerList: [], // 直营区域
      distributionList: [], // 经销
      areaList: [], // 审核区域

      labelCol: { span: 3 },
      wrapperCol: { span: 18 },

      informationlist: [
        { title: '基础设置', herf: '#components' }
        // { title: '上传权限配置', herf: '#components-anchor' },
        // { title: '审核权限配置', herf: '#components-anchor-demo' }
      ],
      form: {
        name: '',
        openAuth: [],
        remark: '',
        uploadBrandList: [],
        uploadPublisherList: [],
        uploadClassifyList: [],
        approvalBrandList: [],
        approvalClassifyList: [],
        approvalNodeList: [],
        approvalAreaList: []
      },
      rules: {
        name: [
          { required: true, message: '请填写标题', trigger: 'blur' },
          { max: 50, message: '标题长度限制20字内', trigger: 'blur' }
        ],
        openAuth: [
          {
            type: 'array',
            required: true,
            message: '请选择权限',
            trigger: 'change'
          }
        ],
        remark: [{ max: 100, message: '备注文案长度限制100字内', trigger: 'blur' }],
        uploadBrandList: [
          {
            type: 'array',
            required: true,
            message: '请选择上传品牌',
            trigger: 'change'
          }
        ],
        uploadPublisherList: [
          {
            type: 'array',
            required: true,
            message: '请选择发布方',
            trigger: 'change'
          }
        ],
        uploadClassifyList: [
          {
            type: 'array',
            required: true,
            message: '请选择素材分类',
            trigger: 'change'
          }
        ],
        approvalBrandList: [
          {
            type: 'array',
            required: true,
            message: '请选择审核品牌',
            trigger: 'change'
          }
        ],
        approvalClassifyList: [{ required: true, message: '请选择素材分类', trigger: 'change' }],
        approvalNodeList: [
          {
            type: 'array',
            required: true,
            message: '请选择审核节点',
            trigger: 'change'
          }
        ],
        approvalAreaList: [
          {
            type: 'array',
            required: true,
            message: '请选择素材区域',
            trigger: 'change'
          }
        ]
      }
    }
  },
  async mounted() {
    this.postThemeDrand() // 上传/审核品牌
    this.postPublisher() // 发布方
    this.postThemeClassify() // 素材分类
    this.postNodeList() // 审核节点
    await this.manufacturer()
    await this.distribution()
    if (this.id && this.id != 'add') {
      await this.postDetail()
    }
  },
  created() {},
  beforeRouteLeave(to, from, next) {
    this.$destroy()
    next()
  },
  methods: {
    // 发布方
    changePublish(value) {
      // this.form.publisher = value
    },
    // 素材分类
    changeMaterialType(value) {
      // this.form.materialType = value
    },
    // 审核-素材分类
    changeCheckMaterial(value) {
      // this.form.checkMaterial = value
    },
    // 素材区域
    changeArea(value) {
      // this.form.area = value
    },
    // 开通权限
    onChangeOpenAuth(value) {
      if (this.form.openAuth.length == 0) {
        if (this.form.openAuth.includes('1')) {
          this.informationlist = [{ title: '基础设置', herf: '#components' }]
        }
      } else if (this.form.openAuth.length == 1) {
        if (this.form.openAuth.includes('1')) {
          this.informationlist = [
            { title: '基础设置', herf: '#components' },
            { title: '上传权限配置', herf: '#components-anchor' }
          ]
        } else if (this.form.openAuth.includes('2')) {
          this.informationlist = [
            { title: '基础设置', herf: '#components' },
            { title: '审核权限配置', herf: '#components-anchor-demo' }
          ]
        }
      } else {
        this.informationlist = [
          { title: '基础设置', herf: '#components' },
          { title: '上传权限配置', herf: '#components-anchor' },
          { title: '审核权限配置', herf: '#components-anchor-demo' }
        ]
      }
    },
    onChange(value) {
      // this.form.postBrands = ''
    },
    // 回显
    postDetail() {
      const that = this
      roleDetail(this.id).then(res => {
        if (res.code == 200) {
          console.log(res.data, '回显')
          let data = res.data
          this.form.name = data.name //角色名称
          this.form.openAuth = data.openAuth.split(',')
          this.form.remark = data.remark //备注
          this.form.uploadBrandList = data.uploadBrandList
            ? data.uploadBrandList.map(item => {
                return item.id
              })
            : [] // 上传品牌

          this.form.uploadPublisherList = data.uploadPublisherList
            ? data.uploadPublisherList.map(item => {
                return item.id
              })
            : []
          // 发布方
          this.form.uploadClassifyList = data.uploadClassifyList
            ? data.uploadClassifyList.map(item => {
                return item.id
              })
            : []
          // 上传——素材分类

          this.form.approvalBrandList = data.approvalBrandList
            ? data.approvalBrandList.map(item => {
                return item.id
              })
            : []

          this.form.approvalClassifyList = data.approvalClassifyList
            ? data.approvalClassifyList.map(item => {
                return item.id
              })
            : [] // 审核——素材分类

          let list1 = this.form.uploadPublisherList
          for (var i = 0; i < list1.length; i++) {
            //不存在则返回-1
            if (this.publisherList.indexOf(list1[i]) == -1) {
              this.publisherList.push({
                key: data.uploadPublisherList[i].id,
                value: data.uploadPublisherList[i].name
              })
            }
          }
          // 上传——素材分类
          let list2 = this.form.uploadClassifyList
          let classifyList = JSON.parse(JSON.stringify(this.classifyList))
          classifyList.map((item, index) => {
            if (item.childList.length > 0) {
              item.childList.map((item2, index2) => {
                if (item2.childList.length > 0) {
                  item2.childList.map((item3, index3) => {
                    if (list2.indexOf(item3.code) == -1 && item3.status == 1) {
                      item2.childList.splice(index3, 1)
                    }
                  })
                } else {
                  if (list2.indexOf(item2.code) == -1 && item2.status == 1) {
                    item.childList.splice(index2, 1)
                  }
                }
              })
            } else {
              if (list2.indexOf(item.code) == -1 && item.status == 1) {
                classifyList.splice(index, 1)
              }
            }
          })
          this.classifyList = classifyList
          // 审核——素材分类
          let arr2 = this.form.approvalClassifyList
          let classifyList2 = JSON.parse(JSON.stringify(this.classifyList2))
          classifyList2.map((item, index) => {
            if (item.childList.length > 0) {
              item.childList.map((item2, index2) => {
                if (item2.childList.length > 0) {
                  item2.childList.map((item3, index3) => {
                    if (arr2.indexOf(item3.code) == -1 && item3.status == 1) {
                      item2.childList.splice(index3, 1)
                    }
                  })
                } else {
                  if (arr2.indexOf(item2.code) == -1 && item2.status == 1) {
                    item.childList.splice(index2, 1)
                  }
                }
              })
            } else {
              if (arr2.indexOf(item.code) == -1 && item.status == 1) {
                classifyList2.splice(index, 1)
              }
            }
          })
          this.classifyList2 = classifyList2
          console.log('=====0000====', that.classifyList2)
          // this.manufacturerList // z 1156
          // this.distributionList // j 1256
          let originList = data.approvalAreaList
          let arr = originList.map((item, index) => {
            var i = {}
            let flag = that.manufacturerList.some(item2 => item2.id == item.id)
            if (!flag) {
              i.id = item.id + '1256'
            } else {
              i.id = item.id + '1156'
            }
            let allArea = [...that.manufacturerList, ...that.distributionList]
            let flag2 = allArea.some(item3 => item3.id == item.id)
            if (!flag2) {
              return ''
            }
            Object.assign(i, {
              key: i.id,
              value: i.id,
              title: item.name
            })
            return i
          })
          arr = arr.filter(item => item)
          this.form.approvalAreaList = arr
            ? arr.map(item => {
                return item.key
              })
            : []
          // 审核——素材区域
          this.form.approvalNodeList = data.approvalNodeList
            ? data.approvalNodeList.map(item => {
                return item.id
              })
            : [] // 审核节点
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },
    anchorClick(e) {
      e.preventDefault()
    },
    gerGood() {
      return document.getElementById('goods')
    },

    postThemeDrand() {
      themeDrand().then(res => {
        if (res.code == 200) {
          this.brandList = res.data
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },
    postPublisher() {
      publisher().then(res => {
        if (res.code == 200) {
          this.publisherList = res.data
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },
    postThemeClassify() {
      let params = ''
      if (this.id && this.id != 'add') {
        params = 0
      }
      themeClassify(params).then(res => {
        if (res.code == 200) {
          console.log('===000000===', res.data)
          // let li = res.data

          this.classifyList = res.data
          this.classifyList2 = res.data
          console.log('===?????===', this.classifyList2)
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },
    // 获取 直营区域
    manufacturer() {
      let data = { departType: 'Z' }
      areaList(data).then(res => {
        if (res.code === 200) {
          this.manufacturerList = res.data
          this.formatStore()
        }
      })
    },
    // 获取经销区域
    distribution() {
      let data = { departType: 'J' }
      areaList(data).then(res => {
        if (res.code === 200) {
          this.distributionList = res.data
          this.formatStore()
        }
      })
    },
    // 获取审核节点
    postNodeList() {
      nodeList().then(res => {
        if (res.code == 200) {
          this.approvalNodeList = res.data
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },
    loadData() {
      let Z = new Promise((resolve, reject) => {
        let data = { departType: 'Z' }
        areaList(data).then(res => {
          if (res.code === 200) {
            this.manufacturerList = res.data
            resolve()
          } else {
            reject(err)
          }
        })
      })
      let J = new Promise((resolve, reject) => {
        let data = { departType: 'J' }
        areaList(data).then(res => {
          if (res.code === 200) {
            this.distributionList = res.data
            resolve()
          } else {
            reject(err)
          }
        })
      })
      Promise.all([Z, J])
        .then(() => {
          this.formatStore()
        })
        .catch(err => {
          callback(err)
        })
    },
    // 格式化 区域
    formatStore() {
      let manufacturerList = this.manufacturerList.map(item => {
        let storeItem = {
          title: item.name,
          value: item.id + '1156',
          key: item.id + '1156',
          id: item.id
        }
        return storeItem
      })
      let distributionList = this.distributionList.map(item => {
        let storeItem = {
          title: item.name,
          value: item.id + '1256',
          key: item.id + '1256',
          id: item.id
        }
        return storeItem
      })
      let treeData = [
        {
          title: '直营',
          value: '1156',
          key: '1156',
          children: manufacturerList
        },
        {
          title: '经销',
          value: '1256',
          key: '1256',
          children: distributionList
        }
      ]
      this.areaList = treeData
    },

    handleBack() {
      this.$router.back()
    },

    preservation() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.requestAddRole()
        } else {
          return false
        }
      })
    },
    async requestAddRole() {
      this.queryParam = this.form
      this.queryParam.approvalAreaList = this.queryParam.approvalAreaList.map(item => {
        return item.slice(0, -4)
      })
      Object.assign(this.queryParam, {
        roleName: this.form.name,
        permissionList: this.form.openAuth
      })
      delete this.queryParam.name
      delete this.queryParam.openAuth
      if (this.id && this.id != 'add') {
        Object.assign(this.queryParam, {
          roleId: this.id
        })
      }
      const res = await roleAdd(this.queryParam)
      if (res.code == 200) {
        this.$router.back()
      } else {
        this.$message.error(res.msg || res.message)
      }
    }
  }
}
</script>
<style scoped lang="less">
/deep/ .ant-tag-checkable {
  border: 1px solid #ccc;
}
.current {
  width: 220px;
}
.edit-title {
  width: 120px;
  color: #333;
  font-size: 14px;
  font-weight: 700;
  cursor: pointer;
  border-right: 1px solid #ccc;
  margin-right: 16px;
}
.brand-box {
  display: flex;
}
.sign {
  margin-right: 12px;
}

.icon-img {
  width: 86px;
  height: 86px;
  object-fit: scale-down;
}

.tip {
  color: #f5222d;
  line-height: 22px;
  margin-top: -8px;
}
.product-wrapper {
  display: flex;
  .img {
    display: block;
    width: 60px;
    height: 60px;
    border: 1px dashed #f5f5f5;
    object-fit: scale-down;
  }
  .text {
    flex: 1;
    margin-left: 10px;
    line-height: 20px;
    font-size: 12px;
    color: #333;
    min-width: 240px;
    .t {
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      word-break: break-all; /* 追加这一行代码 */
      /* autoprefixer: off */
      -webkit-box-orient: vertical;
      /* autoprefixer: on */
    }
  }
}
.footer-box {
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 -1px 6px rgba(0, 0, 0, 0.1);
  position: relative;
  background-color: #fff;
  height: 60px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.edit-font {
  color: #7f7f7f;
  margin-left: 24px;
}
/deep/ .ant-anchor-ink::before {
  background-color: transparent;
}
.record-btn {
  position: absolute;
  right: 55px;
  top: 30%;
  width: 46px;
  height: 100px;
  white-space: pre-wrap;
  text-align: center;
}
</style>
